package com.ronan.imserver.processor;

import cn.hutool.json.JSONUtil;
import com.ronan.common.constant.Constants;
import com.ronan.common.entity.business.BusinessEnum;
import com.ronan.common.entity.business.Ibus;
import com.ronan.common.proto.Business;
import com.ronan.common.proto.Message;
import com.ronan.common.protocol.RIMHeader;
import com.ronan.common.protocol.RIMProtocol;
import com.ronan.imserver.processor.business.BusProcessor;
import com.ronan.imserver.processor.business.BusinessProcessorManager;
import io.netty.channel.Channel;

/**
 * FileName    : com.ronan.imserver.processor
 * Description :
 *
 * @author : ronan
 * @version : 1.0
 * Create Date : 2021/3/17 14:39
 **/
public class BusinessProcessor implements RIMProcessor<Business> {
    /**
     * 处理器
     *
     * @param business 协议
     * @param channel  通道
     */
    @Override
    public void process(Business business, Channel channel) {

        // 根据type找到body数据的class
        Class<? extends Ibus> clazz = BusinessEnum.getClassByCode(business.getType());

        // 根据class找到对应的处理器
        BusProcessor process = BusinessProcessorManager.getProcessByClazz(clazz);
        process.process(business.getFrom(), JSONUtil.toBean(business.getBody(), clazz));

        // TCP_tools测试回复
        message(business,channel);
    }

    public void message(Business business, Channel channel) {
        Message message = Message.newBuilder()
                .setFrom(channel.localAddress().toString())
                .setTo(channel.remoteAddress().toString())
                .setOpe(Constants.OpeConstant.P2P)
                .setType(Constants.MsgTypeConstant.TXT)
                .setBody("服务器收到了你的消息:"+business.getBody())
                .build();

        RIMProtocol msg = new RIMProtocol();
        msg.setBody(message);
        RIMHeader header = new RIMHeader();
        header.setMsgNo(System.currentTimeMillis());
        header.setCommand(Constants.MsgConstant.MESSAGE);
        header.setLength(message.toByteArray().length);
        header.setTimestamp(System.currentTimeMillis());
        msg.setHeader(header);
        channel.writeAndFlush(msg);
    }
}
